package com.singfan.common.util;

import com.singfan.common.SingFanException;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * IP地址相关工具类
 * Author: HanSongHe
 * Date: 2015-07-27 14:46
 * Desc:
 */
public class IPUtil {
    private static boolean isInited = false;

    private static String HOST_IP = null;
    private static String HOST_NAME = null;
    private static String HOST_IP_LAST_SECTION = null;

    /**
     * 获取本机的ip地址
     * @return 本机的ip地址
     */
    public static String getHostIp() {
        if (!isInited){
            init();
        }
        return HOST_IP;
    }

    /**
     * 获取本机的主机名
     * @return 本机的主机名
     */
    public static String getHostName() {
        if (!isInited){
            init();
        }
        return HOST_NAME;
    }

    /**
     * 获取本机ip地址的最后一段
     * @return 本机ip地址的最后一段
     */
    public static String getHostIpLastSection(){
        if (!isInited){
            init();
        }
        return HOST_IP_LAST_SECTION;
    }

    private synchronized static void init() {
        if (!isInited){
            try {
                InetAddress inetAddress = null;
                if(SystemUtil.isWindowsOs() || SystemUtil.isMacOs()){
                    inetAddress = InetAddress.getLocalHost();
                }
                else if(SystemUtil.isLinux()){
                    Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
                    InetAddress ip;
                    while (allNetInterfaces.hasMoreElements()){
                        NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                        Enumeration addresses = netInterface.getInetAddresses();
                        while (addresses.hasMoreElements()){
                            ip = (InetAddress) addresses.nextElement();
                            if (ip != null && ip.isSiteLocalAddress()){
                                inetAddress = ip;
                            }
                        }

                        if(inetAddress != null){
                            break;
                        }
                    }
                }

                if(inetAddress != null){
                    HOST_IP = inetAddress.getHostAddress();
                    HOST_NAME = inetAddress.getHostName();
                    int index = HOST_IP.lastIndexOf(".");
                    HOST_IP_LAST_SECTION = HOST_IP.substring(index + 1);

                    isInited = true;
                }
                else{
                    throw new SingFanException(String.format("IPUtil.init() error: can't get InetAddress in %s !", SystemUtil.getOSName()));
                }
            }
            catch (Exception ex) {
                throw new SingFanException(String.format("IPUtil.init() error: %s !", ex.getMessage()), ex);
            }
        }
    }
}
